package org.usmile.algorithms.huawei.acm;

import java.util.*;

// https://fcqian.blog.csdn.net/article/details/128600757
public class _微服务的集成测试 {
    private static Map<Integer, List<Integer>> prevServices;
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[][] matrix = new int[n][n];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                matrix[i][j] = sc.nextInt();
            }
        }

        int k = sc.nextInt();
        System.out.println(getResult(matrix, n, k));
    }

    public static int getResult(int[][] matrix, int n, int k) {
        // pre用于保存每个点的前驱点
        prevServices = new HashMap<>();
        // 开始统计
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                if (i == j) {
                    continue;
                }
                prevServices.putIfAbsent(i, new ArrayList<>());
                // useTime[i][j] = 1表示服务i启动依赖服务j启动完成，即j的后继点是i；i的前驱点是j
                if (matrix[i][j] == 1) {
                    prevServices.get(i).add(j);
                }
            }
        }

        return dfs(k - 1, matrix);
    }

    public static int dfs(int k, int[][] matrix) {
        if (prevServices.get(k).size() == 0) {
            return matrix[k][k];
        }

        int maxPreTime = 0;
        for (Integer prevService : prevServices.get(k)) {
            maxPreTime = Math.max(maxPreTime, dfs(prevService, matrix));
        }

        return matrix[k][k] + maxPreTime;
    }
}
